//
//  ValiButton.m
//  EachPlan
//
//  Created by 申巧 on 15/6/4.
//  Copyright (c) 2015年 XiaoZhou. All rights reserved.
//

#import "ValiButton.h"
#import "UIColor+mrjColor.h"
#import "NSString+language.h"
@implementation ValiButton
static const int TOTAL_SECOND = 61;

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}
-(id)init{
    self = [super init];
    if(self)
    {
        [self setup];
    }
    return self;
}
-(void)setup{
    self.layer.masksToBounds = YES;
    self.enabled = NO;
    [self setTitleColor:[UIColor colorWithHexString:@"#CCCCCC" andAlpha:1] forState:UIControlStateDisabled];
    [self setTitleColor:[UIColor colorWithHexString:@"#27347D" andAlpha:1] forState:UIControlStateNormal];
    self.contentEdgeInsets = UIEdgeInsetsMake(7, 7, 7, 7);
    self.layer.borderWidth = 1;
    self.layer.cornerRadius = 5;

}
-(void)setTitle:(NSString *)title forState:(UIControlState)state
{
    [super setTitle:title forState:state];
    if (!_oldTitle) {
        _oldTitle = title;
    }
    
}
-(void)validate{
    [self startCountDownSecond];
}

-(void)startCountDownSecond{
    self.isClick = YES;
    _oldTitle = self.titleLabel.text;
    self.userInteractionEnabled = NO;
    self.second = TOTAL_SECOND;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshTime) userInfo:nil repeats:YES];
    [self.timer fire];
    self.enabled = NO;
   
}
-(void)setEnabled:(BOOL)enabled
{
    [super setEnabled:enabled];
    if (enabled) {
        self.layer.borderColor = [UIColor colorWithHexString:@"#27347D" andAlpha:1.0].CGColor;
    }else{
        self.layer.borderColor = [UIColor colorWithHexString:@"#CCCCCC" andAlpha:1.0].CGColor;
    }
}
-(void)refreshTime{
    self.second--;
    
    if (self.second > 0) {
        [self setTitle:[NSString stringWithFormat:@"%ds",self.second] forState:UIControlStateDisabled];
    }
    else{
        [self stopRefreshTime];
    }
}

-(void)stopRefreshTime{
    [self.timer invalidate];
    self.timer = nil;
    self.enabled = YES;
    self.userInteractionEnabled = YES;
    if(self.isClick==YES)
    {
        [self setTitle:[@"app.getcaptha.again" stringForLanguage:[NSString laomi_languageIdentifier]]  forState:UIControlStateNormal];
    }else
    {
        [self setTitle:_oldTitle forState:UIControlStateNormal];
    }
    self.layer.borderColor = [UIColor colorWithHexString:@"#27347D" andAlpha:1].CGColor;
}
-(void)layoutSubviews
{
    [super layoutSubviews];
//    if (self.state == UIControlStateDisabled) {
//         self.layer.borderColor = [UIColor colorWithHexString:@"#CCCCCC" andAlpha:1.0].CGColor;
//    }else{
//        self.layer.borderColor = [UIColor colorWithHexString:@"#0064E6" andAlpha:1.0].CGColor;
//    }
}

@end
